package com.edouardbataille.open.util
{
	import com.edouardbataille.open.meta.MetaField;
	import com.edouardbataille.open.result.Result;
	import com.edouardbataille.open.result.ResultSet;
	
	import mx.core.mx_internal;
	import mx.rpc.AsyncToken;
	import mx.rpc.Fault;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	public class SimpleResponder implements IResponder
	{
		private var clazz : Class;
		
		private var type : Object;
		
		public var token : AsyncToken;
		
		public function SimpleResponder(clazz : Class, type : Object)
		{
			this.clazz = clazz;
			this.type = type;
			token = new AsyncToken ();
		}
		
		public function result(data:Object):void
		{
			var result : * = new clazz ();
			
			var res: ResultSet = ResultSet(data.result);
			
			while (res.hasNext())
			{
				var item : Result = res.next();
				
				for each (var field : MetaField in type.fields)
				{
					result[field.field] = item.result[field.column];
				}
			}
			var event : ResultEvent = ResultEvent.createEvent(result, token);
			token.dispatchEvent(event);
			event.mx_internal::callTokenResponders ();
		}
		
		public function fault(info:Object):void
		{
			var fault : Fault = info.fault;
			var event : FaultEvent = FaultEvent.createEvent(fault, token);
			token.dispatchEvent(event);
			event.mx_internal::callTokenResponders ();
		}

	}
}